/*
** sh.c for 42sh in /home/guina_b/
** 
** Made by benoit guina
** Login   <guina_b@epitech.net>
** 
** Started on  Fri Jan 01 00:00:00 2010 benoit guina
** Last update Fri Jan 01 00:00:00 2010 benoit guina
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"
#include "error.h"
#include "escaping.h"
#include "token.h"
#include "lexer.h"
#include "parser.h"
#include "jobmgr.h"
#include "term.h"
#include "env.h"
#include "sh.h"

int sh_init(t_sh *sh, char **env)
{
  if ((sh->env = env_init(env, 0)))
  {
    if ((sh->term = term_init(sh->env)))
    {
      if ((sh->jobmgr = jobmgr_init()))
        return (0);
      term_free(sh->term);
    }
    env_free(sh->env);
  }
  error_print(SH_ERR_INIT);
  return (-1);
}

void sh_free(t_sh *sh)
{
  env_free(sh->env);
}

int sh_execute_input(t_sh *sh, char *input)
{
  char *s;
  t_token *tokens;
  struct s_job *jobs;

  while ((s = escaping_strtok(&input, ";")))
  {
    printf("new job: '%s'\n", s);
    if ((tokens = lexer_build_tokens(s)))
    {
      jobs = parser(sh, tokens);
      list_apply(tokens, (void (*)())token_free);
      if (jobs)
      {
        list_apply1(jobs, (void (*)())jobmgr_add_job, sh->jobmgr);
        /*jobs_execute(jobs)? or will it be up to the jobmgr?*/
      }
    } 
  }
  sh = sh;
  return (0);
}

int sh_run(t_sh *sh, char *arg_input)
{
  char *input;

  if (arg_input)
  {
    sh_execute_input(sh, arg_input);
    return (sh->exit_status);
  }
  while ((input = term_get_input(sh->term)) &&
          sh_execute_input(sh, input) != 1);
  return (sh->exit_status);
}
